#!/bin/bash
# CCPM Configuration
# This ensures all GitHub issues are created in the correct repository

# Function to detect repository from git remote with enhanced error handling
get_github_repo() {
    local remote_url=$(git remote get-url origin 2>/dev/null)
    
    if [ -z "$remote_url" ]; then
        echo "Error: No git remote found" >&2
        return 1
    fi
    
    # Handle HTTPS, SSH, and SCP-style URLs
    local repo="$remote_url"
    # Remove various GitHub URL prefixes
    repo=$(echo "$repo" | sed -E 's#^https://github\.com/##')
    repo=$(echo "$repo" | sed -E 's#^git@github\.com:##')
    repo=$(echo "$repo" | sed -E 's#^ssh://git@github\.com/##')
    repo=$(echo "$repo" | sed -E 's#^ssh://github\.com/##')
    # Remove .git suffix if present
    repo=$(echo "$repo" | sed 's#\.git$##')
    
    # Validate format
    if [[ ! "$repo" =~ ^[^/]+/[^/]+$ ]]; then
        echo "Error: Invalid repository format: $repo" >&2
        return 1
    fi
    
    echo "$repo"
}

# Allow environment override
if [ -n "$CCPM_GITHUB_REPO" ]; then
    GITHUB_REPO="$CCPM_GITHUB_REPO"
else
    GITHUB_REPO=$(get_github_repo) || exit 1
fi

# Extract owner and repo name
GITHUB_OWNER=$(echo $GITHUB_REPO | cut -d/ -f1)
GITHUB_REPO_NAME=$(echo $GITHUB_REPO | cut -d/ -f2)

# Export for gh CLI
export GH_REPO="$GITHUB_REPO"

# Validate repository exists (optional - can be disabled for performance)
if [ "${CCPM_SKIP_REPO_VALIDATION:-false}" != "true" ]; then
    if ! gh repo view "$GITHUB_REPO" >/dev/null 2>&1; then
        echo "Warning: Repository $GITHUB_REPO not accessible. Please ensure:" >&2
        echo "  1. Repository exists on GitHub" >&2
        echo "  2. You have write access" >&2
        echo "  3. You're authenticated with gh CLI (run: gh auth login)" >&2
    fi
fi

# Wrapper function with error handling and logging
gh_issue_create() {
    echo "Creating issue in: $GITHUB_REPO" >&2
    gh issue create --repo "$GITHUB_REPO" "$@"
}

# Export functions for use in other scripts
export -f get_github_repo
export -f gh_issue_create